package com.lvhx.springboot.partitioner;


import com.lvhx.springboot.springbatch.base.DataConsumer;
import com.lvhx.springboot.springbatch.base.Parameters;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemStreamException;
import org.springframework.batch.item.support.AbstractItemStreamItemWriter;

import java.util.List;

public class CustomItemWriter<T> extends AbstractItemStreamItemWriter<T> {
    private Parameters parameters;
    private DataConsumer<T> dataConsumer;

    @Override
    public void write(List<? extends T> items) throws Exception {
        for (T item : items) {
            dataConsumer.consumeData(item, parameters);
        }
    }

    @Override
    public void close() throws ItemStreamException {
        parameters = null;
        dataConsumer = null;
        super.close();
    }

    @SuppressWarnings("unchecked")
    @Override
    public void open(ExecutionContext executionContext)
            throws ItemStreamException {
        parameters = (Parameters) executionContext.get("PARAMETERS");
        dataConsumer = (DataConsumer<T>) executionContext.get("CONSUMER");
        super.open(executionContext);
    }
}
